package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.DishCategoryMapper;
import com.zhentao.mapper.DishInfoMapper;
import com.zhentao.pojo.Inventory;
import com.zhentao.service.InventoryService;
import com.zhentao.mapper.InventoryMapper;
import com.zhentao.util.Result;
import org.example.dish_pojo.DishCategory;
import org.example.dish_pojo.DishInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @author Lenovo
* @description 针对表【inventory(菜品库存表（按门店管理）)】的数据库操作Service实现
* @createDate 2025-08-01 11:50:23
*/
@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory>
    implements InventoryService{
    @Autowired
    InventoryMapper inventoryMapper;
    @Autowired
    private DishInfoMapper dishInfoMapper;
    @Autowired
    private DishCategoryMapper dishCategoryMapper;
    @Override
    public Result findainven(Inventory inventory) {
        Page<Inventory> page=new Page<>(inventory.getPagenum(),inventory.getPagesize());
        QueryWrapper<Inventory> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(inventory.getDishId()!=null,"dish_id",inventory.getDishId());
        queryWrapper.like(inventory.getTypeId()!=null,"type_id",inventory.getTypeId());
        inventoryMapper.selectPage(page,queryWrapper);
        List<Inventory> list=page.getRecords();
        if (list.size()>0){
            for (Inventory i : list) {
                Integer dishid=i.getDishId();
                DishInfo dishInfo = dishInfoMapper.selectById(dishid);
                if(dishInfo!=null){
                    i.setCname(dishInfo.getName());
                }
            }
            for (Inventory t : list) {
                Integer typeid= t.getTypeId();
                DishCategory dishCategory = dishCategoryMapper.selectById(typeid);
                if(dishCategory!=null){
                    t.setTname(dishCategory.getCategoryName());
                }
            }
        }
        // 名称模糊查询（如果传入 cname，则在内存中过滤；数据量大时建议改为 SQL join）
        if (inventory.getCname() != null && !inventory.getCname().isEmpty()){
            list.removeIf(item -> item.getCname()==null || !item.getCname().contains(inventory.getCname()));
            page.setRecords(list);
            page.setTotal(list.size());
        }
        return Result.OK(page);
    }

    @Override
    public Result updateThresholds(Integer inventoryId, Integer warningStock, Integer highThreshold) {
        Inventory inv = this.getById(inventoryId);
        if (inv == null) {
            return Result.ERROR("库存记录不存在");
        }
        if (warningStock != null) {
            inv.setWarningStock(warningStock);
        }
        if (highThreshold != null) {
            inv.setHighThreshold(highThreshold);
        }
        this.updateById(inv);
        return Result.OK(inv);
    }

    @Override
    public void export(Inventory inventory, HttpServletResponse response) {
        Page<Inventory> page=new Page<>(1,Integer.MAX_VALUE);
        QueryWrapper<Inventory> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(inventory.getDishId()!=null,"dish_id",inventory.getDishId());
        queryWrapper.like(inventory.getTypeId()!=null,"type_id",inventory.getTypeId());
        inventoryMapper.selectPage(page,queryWrapper);
        List<Inventory> list=page.getRecords();
        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment; filename=inventory.csv");
        try{
            PrintWriter writer = response.getWriter();
            writer.println("菜品ID,类型ID,单位,库存,盘点时间,预警阈值,上限阈值");
            for(Inventory i: list){
                writer.printf("%d,%d,%s,%d,%tF %<tT,%d,%d%n",
                        i.getDishId()==null?0:i.getDishId(),
                        i.getTypeId()==null?0:i.getTypeId(),
                        i.getDishdanwei()==null?"":i.getDishdanwei(),
                        i.getCurrentStock()==null?0:i.getCurrentStock(),
                        i.getDate()==null?new java.util.Date():i.getDate(),
                        i.getWarningStock()==null?0:i.getWarningStock(),
                        i.getHighThreshold()==null?0:i.getHighThreshold());
            }
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}




